package com.bytz.interceptors;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.util.StrUtil;
import com.bytz.common.exception.BytzBootException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.filter.OrderedFilter;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

@Component
public class AdminSimpleCsrfInterceptor extends OncePerRequestFilter implements OrderedFilter {

    /**
     * Filter的加载顺序
     */
    private final static int ORDER = Integer.MIN_VALUE + 1;

    @Value("${post.filter-fields}")
    private List<String> matchFields;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String t = request.getParameter("_t");
        if (StrUtil.isNotBlank(t)) {
            String[] s = t.split("_");
            if (s.length != 2) {
                throw new BytzBootException("无效CSRF Token");
            }

            if (!Objects.equals(s[0], Base64Decoder.decodeStr(s[1]))) {
                throw new BytzBootException("无效CSRF Token");
            }
        }

        if (StringUtils.equals(request.getMethod(), HttpMethod.POST.name())) {

            PostRequestWrapper postRequestWrapper = new PostRequestWrapper(request);

            PostInterceptorFilter postInterceptorFilter = new PostInterceptorFilter();
            postInterceptorFilter.filterFields(postRequestWrapper.getBodyString(), matchFields);

//            JsoupUtil.valid(postRequestWrapper.getBodyString());

            filterChain.doFilter(postRequestWrapper, response);
            return;
        }

        filterChain.doFilter(request, response);
    }

    @Override
    public int getOrder() {
        return ORDER;
    }
}